//
//  InstantMessaging.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/3/27.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import Photos
import SwiftyJSON

class sonImageView: UIImageView {
}

class InstantMessaging: UIViewController {

    @IBOutlet weak var messageCollectionView: IMUIMessageCollectionView!
    @IBOutlet weak var soninputView: HMUIInputView!
    var imageViewArr = [sonImageView]()
    let imageManage: PHCachingImageManager = PHCachingImageManager()

    // 用户id
    var im_userId = ""
    // 医生id
    var im_doctorId = ""
    /// 咨询id
    var im_consultId = ""
    var doctorProfile = TIMUserProfile()  //IM 方法获取对方个人信息
    var userProfile = JSON() //对方个人信息（后台数据获取）
    /// 拉取已经存在的数据
    var dataAry = Array<Any>()
    var conversation = TIMConversation()
    /// 记录聊天数量
    var recordCount = 0
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        
        // 获取聊天天数
        NetRequestTool.shareInstance.met = .get
        NetRequestTool.request(url: "doctor/consult/chat-count", parameters: ["consultId":self.im_consultId as Any], success: { (chJson) in
            self.recordCount = chJson["data"]["count"].intValue
        }, fail: { (chCode, chErr) in
            print("======>>", chCode)
        }) {}

        
     //   let indexPath = IndexPath.init(item: self.messageCollectionView.chatDataManager.count - 1, section: 0)
       // self.messageCollectionView.messageCollectionView.setContentOffset(CGPoint.init(x: 0, y: 300), animated: true)
//        let con:TIMConversation = HMPlatform.getSomeoneConversation(im_doctorId)
//        let ary = con.getLastMsgs(10)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.messageCollectionView.delegate = self //as! IMUIMessageMessageCollectionViewDelegate
        self.soninputView.inputViewDelegate = self //as! IMUIInputViewDelegate
        self.soninputView.instantMess = self
        self.soninputView.messageCollectionView = self.messageCollectionView
        self.soninputView.conversation = self.conversation
        
    self.messageCollectionView.messageCollectionView.register(MessageEventCollectionViewCell.self, forCellWithReuseIdentifier: self.description)

        //设置消息回调
        HMPlatform.sharePlatform.newMessageBlock = {
            (ary: [Any]) in
            let message = self.dataAry[0] as! TIMMessage
            let  user :TIMUserProfile = message.getSenderProfile()
            
            if user.identifier == HMLoginParam.share.getCurrentId {
                NetRequestTool.shareInstance.met = .post
                NetRequestTool.request(url: "doctor/consult/inc-chat", parameters: ["consultId":self.im_consultId as Any], success: { (chJson) in
                    self.recordCount = chJson["data"]["count"].intValue
                }, fail: { (chCode, chErr) in }) {
                    
                }
            }

        
            HMElem.serviceAnalysimMessage(list: ary, profile: self.userProfile) { (index, message, info, isOutGoing) in
                self.analysim(index, message, info, isOutGoing)
            }
        }
        
     
        HMElem.serviceAnalysimMessage(list: dataAry, profile: userProfile) { (index, message, info, isOutGoing) in
             self.analysim(index, message, info, isOutGoing)
        }
    }
    
    
    func analysim(_ index: Int, _ message: TIMMessage, _ info: HMImUserInfo, _ isOutGoing: Bool) {
        let cnt = message.elemCount()
        var maceAry = Array<String>()
        var elem = TIMElem()
        var _elemType: AnyClass!
        if cnt > 0 {
            for i in 0..<cnt {
                elem = message.getElem(i)
                // 获取类型转换
                if (elem.isKind(of: TIMTextElem.classForCoder())) {
                    _elemType = TIMTextElem.classForCoder()
                    let text_elem = elem as! TIMTextElem
                    maceAry.append(text_elem.text)
                }else if (elem.isKind(of: TIMImageElem.classForCoder())) {
                    _elemType = TIMImageElem.classForCoder()
                    
                }else if (elem.isKind(of: TIMSoundElem.classForCoder())) {
                    _elemType = TIMSoundElem.classForCoder()
                }else if (elem.isKind(of: TIMFaceElem.classForCoder())) {
                    _elemType = TIMFaceElem.classForCoder()
                    let face_elem = elem as! TIMFaceElem
                    //
                    let str = NSString.init(data: face_elem.data, encoding: String.Encoding.utf8.rawValue)
                    maceAry.append("\(str! as String)")
                    //                             maceAry.append("[\(face_elem.index)]")
                }else if (elem.isKind(of: TIMCustomElem.classForCoder())) {
                    _elemType = TIMCustomElem.classForCoder()
                }else {
                    _elemType = TIMElem.classForCoder()
                }
            }
            
            
            if _elemType == TIMTextElem.self || _elemType == TIMFaceElem.self {
                // self.textElem(maceStr, info, isOutGoing)
                self.textElem(maceAry, info, isOutGoing, index: 0)
            }else if _elemType == TIMImageElem.self {
                self.imageElem(elem, info, isOutGoing)
            }else if _elemType == TIMSoundElem.self {
                self.soundElem(elem, info, isOutGoing)
            }else if _elemType == TIMCustomElem.self {
                print("(自定义格式文件)")
                self.customElem(elem,info,isOutGoing)
            }else {
                print("(其他格式文件)")
            }
            
            
        }else { // 0 如果是零就没信息啦
            print("没有信息")
        }
    }

    // Text Elem or Face Elem
    func textElem(_ maceAry:Array<String>,  _ userInfo:HMImUserInfo, _ isOutGoing:Bool, index: Int) {
        
//        let messge =
//        let mutStr = NSMutableAttributedString.init(string: messge, attributes: [kCTFontAttributeName : UIFont.systemFont(ofSize: 15),])
        
        if maceAry.count > 1 {
            
//            var textView = UITextView.init()
            var attrStr =  String()
            for str in maceAry {
                if str.hasPrefix("[") && str.hasSuffix("]") {
                    
//                    let num = str[Range.init(NSRange.init(location:1, length: str.count - 2))!]
//
//                    let path = Bundle.main.path(forResource: "emoticon/\(num)", ofType: "gif")
//                    let data =  NSData.init(contentsOfFile: path!)
//                    let newdata = data! as Data
//
//                    let textAttachment = NSTextAttachment.init()//NSTextAttachment.init(data: newdata, ofType: "gif")
//                     textAttachment.image = UIImage.init(data: newdata)
//                     textAttachment.bounds =  CGRect.init(x: 0, y: 0, width: 20, height: 20)
                    
//                    let newStr =  NSAttributedString.init(string: str) //NSAttributedString.init(attachment: textAttachment)
                   
//                    attrStr += "\(newStr)"
                    attrStr += str
                }else { // 不是表情
                    attrStr += str
                }
            }
//            textView.attributedText = NSAttributedString.init(string: attrStr)
//
//            textView.frame = CGRect.init(x: 0, y: 0, width: 200, height: 200)
//            self.view.addSubview(textView)
            
            let mesg = MessageModel(text: attrStr, isOutGoing: isOutGoing)
            mesg.messageStatus = .success
            mesg.fromUser = userInfo
            self.messageCollectionView.appendMessage(with: mesg)
            
        }else {
                    let mesg = MessageModel(text: maceAry[0] as String, isOutGoing: isOutGoing)
                    mesg.messageStatus = .success
                    mesg.fromUser = userInfo
                    self.messageCollectionView.appendMessage(with: mesg)

        }
     
        
    }
    
    // Image Elem
    func imageElem(_ elem:TIMElem, _ userInfo:HMImUserInfo, _ isOutGoing:Bool) {
        let img_elem = elem as! TIMImageElem
        
        //  print("=====>>", img_elem.imageList)
        if !(img_elem.path.contains("http://")) {
            // 图片保存路径
            let docPath: String = "\(NSHomeDirectory())/Documents/"
            
            /* 保存本图片的所有规格，目前最多包含三种规格: 缩略图、大图、原图，
             每种规格保存在一个TIMImage对象中 */
            let imgList = img_elem.imageList
            // 不循环
            //  var i = 0
            
            if imgList?.count != 0 {
                //                        let url =  URL.init(string:  img_elem.path)  //获取原图路径
                let  filePath =  InstantMessaging.getUserFilePath()
                
                let url = String.interceptString(value: img_elem.path, character: "/", isPrefix: false, isFirst: false)
                let newUrl = url.suffix(url.count - 1)
                
                // 设置保存的文件名称  原图名称  + _1x （缩略图） ， _2x (大图)
                var pic_path = docPath  + "\(newUrl)_1x.jpg"   // 不带
                let file = filePath.appendingPathComponent("\(newUrl)_1x.jpg")  //带  fill://
                
                print("======>", pic_path , "\n ====>", file)
                
                do { // 判断路径上d是否有原文件
                    try Data.init(contentsOf: file)
                    
                    print("存在")
                    let mesg = MessageModel.init(imagePath: pic_path, isOutGoing: isOutGoing)
                    mesg.messageStatus = .success
                    mesg.fromUser = userInfo
                    self.messageCollectionView.appendMessage(with: mesg)
                    
                }catch {
                    print("path is not exist")
                    
                    // 拿缩略图
                    let image = imgList![0] as! TIMImage
                    // 下载
                    image.getImage(pic_path, succ: {
                        print("成功====>>", image, pic_path)
                        let mesg = MessageModel.init(imagePath: pic_path, isOutGoing: isOutGoing)
                        mesg.messageStatus = .success
                        mesg.fromUser = userInfo
                        self.messageCollectionView.appendMessage(with: mesg)
                    }, fail: { (code, err) in
                        print("失败===>>", image)
                    })
                    
                    
                }
                
            }else {
                print("img list count is zero  (没有图组)")
            }
        }else {
            print(" is img path Illegal format (格式不对)")
        }
    }

    // Sound Elem
    func soundElem(_ elem:TIMElem, _ userInfo:HMImUserInfo, _ isOutGoing:Bool) {
        let sound_elem = elem as! TIMSoundElem
        
        // 保存语音的路径
        var docPath: String = "\(NSHomeDirectory())/Documents/"
        
        //  var pic_path = docPath    //+ "\(newUrl)_1x.jpg"   // 不带
        print("=======>>>>", sound_elem.path)
        
        if sound_elem.path != "" && sound_elem.path != nil {
            
            //截取路径中的文件名称
            let url = String.interceptString(value: sound_elem.path, character: "/", isPrefix: false, isFirst: false)
            let fillName = url.suffix(url.count - 1)
            print("------>文件名称", fillName)
            let  filePath =  InstantMessaging.getUserFilePath()
            let file = filePath.appendingPathComponent(String(fillName))
            
            if InstantMessaging.isFileExist(fileName: String(fillName)) {
                print("存在路径")
                //                        let path =  pic_path + fillName
                let mesg = MessageModel.init(voicePath: "\(file)", duration: CGFloat(sound_elem.second), isOutGoing: isOutGoing)    // init(imagePath: path, isOutGoing: isOutGoing)
                mesg.messageStatus = .success
                mesg.fromUser = userInfo
                self.messageCollectionView.appendMessage(with: mesg)
            }else {
                //                        print("1111")
                
                let now:Date = Date()
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd-hh-mm-ss"
                // 设置保存的文件名称
                let path = docPath + "\(dateFormatter.string(from: now))-OtherSound.wav"
                sound_elem.getSoundToFile(path, succ: {
                    
                    let mesg = MessageModel.init(voicePath: "\(file)", duration: CGFloat(sound_elem.second), isOutGoing: isOutGoing)    // init(imagePath: path, isOutGoing: isOutGoing)
                    mesg.messageStatus = .success
                    mesg.fromUser = userInfo
                    self.messageCollectionView.appendMessage(with: mesg)
                    
                }, fail: { (code, err) in
                    print("获取失败")
                })
                
            }
            
        }else {
            print("sound path is not (没有文件路径)")
        }
    }

    // Custom Elem
    func customElem(_ elem:TIMElem, _ userInfo: HMImUserInfo, _ isOutGoing:Bool){
       
        let cus_elem = elem as! TIMCustomElem
        /*
        if  cus_elem.data != nil {
            let str = String.init(data: cus_elem.data, encoding: String.Encoding.utf8)
    
            let ary: Array<String> = (str?.components(separatedBy: ","))!
         
            var newAry = Array<String>()
            for item in ary {
                let range = item.range(of: ":")
                var subStrAfter = String(item.suffix(from: (range?.upperBound)!))  //后
                var subStrFront = String(item.prefix(upTo: (range?.lowerBound)!))  //前
         
                subStrAfter =  subStrAfter.trimmingCharacters(in: .whitespaces)
                print("===》〉", subStrAfter)
                var newSubStr = ""
                if subStrAfter.contains("\"") {  //包含
                    newSubStr = subStrFront + ":" + subStrAfter
                    newAry.append(newSubStr)
         
                }else { //不包含
                    if subStrAfter.contains("'") {
                        let nstr = subStrAfter.replacingOccurrences(of: "'", with: "\"")
                        newSubStr = subStrFront + ":" + nstr
                        newAry.append(newSubStr)
                    }else {
         
                        newSubStr = subStrFront + ":" + "\"" + subStrAfter + "\""
                        newAry.append(newSubStr)
                    }
                }
            }
         
            let newJsonStr = newAry.joined(separator: ",")
            let dic = self.getJSONStringToDictionary(JSONString: newJsonStr)
        }*/
      
       
        
        let mesg = MessageModel.init(data: cus_elem.data, isOutGoing: isOutGoing, type: "药物建议")  //init(voicePath: "\(file)", duration: CGFloat(sound_elem.second), isOutGoing: isOutGoing)    // init(imagePath: path, isOutGoing: isOutGoing)
        mesg.messageStatus = .success
        mesg.fromUser = userInfo
        self.messageCollectionView.appendMessage(with: mesg)
    }
}

// MARK: - IMUIInputViewDelegate
extension InstantMessaging: IMUIInputViewDelegate {
           // 发送信息
            func sendTextMessage(_ messageText: String) {
               let outGoingmessage = MessageModel.init(text: messageText, isOutGoing: true)
                self.messageCollectionView.appendMessage(with: outGoingmessage)
                HMElem.structureMessage(conversation, elemType: TIMTextElem.classForCoder(), value: messageText, succ: {
                    outGoingmessage.messageStatus = .success;
                    self.messageCollectionView.updateMessage(with: outGoingmessage)
                    //成功
                }) { (code, msg) in
                    //失败
                    outGoingmessage.messageStatus = .failed;
                    self.messageCollectionView.updateMessage(with: outGoingmessage)
                }
                
            }
        
            func switchIntoRecordingVoiceMode(recordVoiceBtn: UIButton) {
              print("这个什么鬼？")
            }
            // 点表情
            func switchToEmojiMode(cameraBtn: UIButton) {
                print("switchToEmojiMode")
            }
            // 发送图片时
            func didShootPicture(picture: Data) {
                let imgPath = self.getPath()
        
                let imageView = sonImageView()
                self.imageViewArr.append(imageView)
                
                do { // 判断路径是否，有文件
                    try picture.write(to: URL(fileURLWithPath: imgPath))
                    DispatchQueue.main.async {

                       
                        let outGoingmessage = MessageModel.init(imagePath: imgPath, isOutGoing: true)
                        outGoingmessage.messageStatus = .sending
                        self.messageCollectionView.appendMessage(with: outGoingmessage)
                        HMElem.structureMessage(self.conversation, elemType: TIMImageElem.classForCoder(), value: imgPath, succ: {
                            outGoingmessage.messageStatus = .success
                            self.messageCollectionView.updateMessage(with: outGoingmessage)
                            
                        }, fail: { (code, err) in
                            outGoingmessage.messageStatus = .failed
                            self.messageCollectionView.updateMessage(with: outGoingmessage)
                        })
                    }
                } catch {
                   // 读取错误
                    print("write image file error")
                }
        
            }
            // 视频
            func finishRecordVideo(videoPath: String, durationTime: Double) {
                let outGoingmessage = MessageModel(videoPath: videoPath, isOutGoing: true)
                let inCommingMessage = MessageModel(videoPath: videoPath, isOutGoing: false)
                self.messageCollectionView.appendMessage(with: outGoingmessage)
                self.messageCollectionView.appendMessage(with: inCommingMessage)
            }
            // 语音发送
            func finishRecordVoice(_ voicePath: String, durationTime: Double) {
                
                let outGoingmessage = MessageModel.init(voicePath: voicePath, duration: CGFloat(durationTime), isOutGoing: true)
                outGoingmessage.messageStatus = .sending
                self.messageCollectionView.appendMessage(with: outGoingmessage)
                // value 传 元组
                HMElem.structureMessage(self.conversation, elemType: TIMSoundElem.classForCoder(), value: (voicePath, durationTime), succ: {
                    outGoingmessage.messageStatus = .success
                    self.messageCollectionView.updateMessage(with: outGoingmessage)
                    
                }, fail: { (code, err) in
                    outGoingmessage.messageStatus = .failed
                    self.messageCollectionView.updateMessage(with: outGoingmessage)
                })
                
                
            }
    
            func didSeletedGallery(AssetArr: [PHAsset]) {
                for asset in AssetArr {
                    switch asset.mediaType {
                    case .image:
        
                        //        PHImageRequestOptions *options = [[PHImageRequestOptions alloc]init];
                        //        options.synchronous  = YES;
                        //        options.networkAccessAllowed = YES;
                        //        PHCachingImageManager *imageManage = [[PHCachingImageManager alloc] init];
                        //
                        //        [imageManage requestImageForAsset: asset
                        //        targetSize: CGSizeMake(asset.pixelWidth, asset.pixelHeight)
                        //        contentMode: PHImageContentModeAspectFill
                        //        options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                        //        NSData *imageData = UIImagePNGRepresentation(result);
                        //        NSString *filePath = [self getPath];
                        //        if ([imageData writeToFile: filePath atomically: true]) {
                        //        [imagePathArr addObject: @{@"mediaPath": filePath, @"mediaType": @"image"}];
                        //        }
                        //        }];
        
        
                        let option = PHImageRequestOptions()
                        option.isSynchronous = true
                        option.isNetworkAccessAllowed = true
        
                        imageManage.requestImage(for: asset, targetSize: CGSize(width: asset.pixelWidth/4, height: asset.pixelHeight/4), contentMode: .aspectFill, options: option, resultHandler: { [weak self] (image, _) in
//                            let imageData = UIImagePNGRepresentation(image!)
//                            let imageData = UIImageJPEGRepresentation(image!, 2.0)
                            
                            // (datas as! [Data], imgAssets as! [Any])
                            let img =  HMPhotoView.requesHeadImages(photos: [image!], assets: nil)
                            self?.didShootPicture(picture: img.datas[0])
                        })
                        break
                    default:
                        break
                    }
                }
            }
        
            func getPath() -> String {
                var recorderPath:String? = nil
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yy-MMMM-dd"
                recorderPath = "\(NSHomeDirectory())/Documents/"
                recorderPath?.append("\(NSDate.timeIntervalSinceReferenceDate)")
                return recorderPath!
            }
    }
    
// MARK - IMUIMessageMessageCollectionViewDelegate
extension InstantMessaging: IMUIMessageMessageCollectionViewDelegate {
// custom view
    func messageCollectionView(messageCollectionView: UICollectionView, forItemAt: IndexPath, messageModel: IMUIMessageProtocol) -> UICollectionViewCell? {
        if messageModel is MessageEventModel {
            
            let cellIdentify = MessageEventCollectionViewCell.self.description()
            
            let cell = messageCollectionView.dequeueReusableCell(withReuseIdentifier: cellIdentify, for: forItemAt) as! MessageEventCollectionViewCell
            
            let message = messageModel as! MessageEventModel
        
            cell.presentCell(eventText: message.eventText) // 模版类型 text\Image\Voide..
            return cell  // 这里创建Cell 模版
        } else {
            return nil
        }
        
    }
    
    
        func messageCollectionView(messageCollectionView: UICollectionView, heightForItemAtIndexPath forItemAt: IndexPath, messageModel: IMUIMessageProtocol) -> NSNumber? {
            if messageModel is MessageEventModel {
                return 20.0
            } else {
                return nil
            }
        }
        // 点内容时事件
        func messageCollectionView(didTapMessageBubbleInCell: UICollectionViewCell, model: IMUIMessageProtocol) {
            self.showToast(alert: "tap message bubble")
            
        }
        // 点头像
        func messageCollectionView(didTapHeaderImageInCell: UICollectionViewCell, model: IMUIMessageProtocol) {
            self.showToast(alert: "tap header image")
        }
         // 点消息状态
        func messageCollectionView(didTapStatusViewInCell: UICollectionViewCell, model: IMUIMessageProtocol) {
            self.showToast(alert: "tap status View")
        }
        
        // 将显示消息单元
        func messageCollectionView(_: UICollectionView, willDisplayMessageCell: UICollectionViewCell, forItemAt: IndexPath, model: IMUIMessageProtocol) {
            print("---------->>\(forItemAt)----->\(model)")
        }
        // 没有最终的显示
        func messageCollectionView(_: UICollectionView, didEndDisplaying: UICollectionViewCell, forItemAt: IndexPath, model: IMUIMessageProtocol) {
            
        }
        //将开始拖动
        func messageCollectionView(_ willBeginDragging: UICollectionView) {
            self.soninputView.hideFeatureView()
        }
        
        func showToast(alert: String) {
            let toast = UIAlertView(title: alert, message: nil, delegate: nil, cancelButtonTitle: nil)
            toast.show()
            toast.dismiss(withClickedButtonIndex: 0, animated: true)
        }
    }

extension InstantMessaging {
    /// 获取用户路径
    static func getUserFilePath()-> URL {
        let manager = FileManager.default
        let urlForDocument = manager.urls(for: .documentDirectory, in: .userDomainMask)
        let url = urlForDocument[0] as URL
        return url
    }
    
    static func isFileExist(fileName: String) -> Bool{
        
        
        let docPath: String = "\(NSHomeDirectory())/Documents/"
        var pic_path = docPath + fileName
//        print("打印路径", pic_path)
        let manager = FileManager.default
        let result =  manager.fileExists(atPath: pic_path)

        return result
      
    }
}
